<?php

class Photo extends Model {

    public $id;
    public $name;
    public $favorite;
    public $user_id;
    public $view;

    public function __construct() {
        parent::__construct();
        //$this->_initialize($params);
    }

    public function add($name, $user_id) {
        $txtErr = '';
        if (trim($name) == '') {
            return array('updated' => 0, 'txtErr' => 'Photo name is empty');
        }
        $sql = sprintf("INSERT INTO `l4_photo`(`name`, `user_id`)
				VALUES('%s', %s)", mysql_real_escape_string($name), $user_id);

        $this->db->startTrans();
        $this->db->queryshort($sql, DB_NAME);
        $row_affected = $this->db->affectedRow();

        if ($row_affected > 0) {
            $last_id = $this->db->getLastId();
            $txtErr = self::upload($last_id);
            if (trim($txtErr) != '') {
                $this->db->rollback();
                return array('updated' => 0, 'txtErr' => $txtErr);
            }
            //Create thumbnail
            $superThis = & getInstance();
            $superThis->library('image');
            image::createThumb("img/{$last_id}.jpeg", "img/thumb/{$last_id}.jpeg", 80);
            $this->db->commit();
            return array('updated' => 1, 'id' => $last_id);
        } else {
            return false;
        }
    }

    public function delete($id) {
        if (empty($id)) {
            return false;
        }

        $sql = "DELETE FROM `l4_photo` WHERE `id`='%s'";
        $sql = sprintf($sql, $id);
        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow > 0) {
            //Delete image ...///////////Process more.
            @unlink("img/{$id}.jpeg");
            return true;
        } else {
            return false;
        }

        return false;
    }

    public function update($ip) {
        $sql = "UPDATE l5_sessions SET last_activity=" . time() . ", login_times=login_times+1 WHERE ip_address='%s'";
        $sql = sprintf($sql, $ip);

        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow > 0) {
            //return 'User updated successfully.';
            return true;
        } else {
            return false;
            //return 'User updated successfully.';
        }

        return false;
    }

    public function gets($idLog, $idView, array $ids = NULL) {
        if (empty($idLog) || empty($idView)) {
            return false;
        }

        $sql = "SELECT *,
                (SELECT COUNT(*) FROM `l4_like_photo` b WHERE a.`id`=b.`photo_id`) AS `numLike`,
                (SELECT COUNT(*) FROM `l4_like_photo` b WHERE b.`user_id`= {$idLog} AND a.`id`=b.`photo_id`) AS `liked`,
                (SELECT COUNT(*) FROM `l4_photo_view` c WHERE c.`photo_id`= a.`id`) AS `numView`
                FROM `l4_photo` a
                WHERE `user_id` = {$idView}";
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            return $this->db->getArrayObject();
        }
        return NULL;
    }

    public function like($id, $user_id) {
        //Check if this user like this photo or not...
        if ($this->_likeExisted($id, $user_id)) {
            return false;
        }
        $sql = "INSERT INTO `l4_like_photo`(`photo_id`,`user_id`) VALUES({$id}, {$user_id})";
        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow > 0) {
            //Get number of like....
            return $this->_countLike($id);
        } else {
            return false;
        }

        return false;
    }

    public function view($id, $user_id) {
        if (empty($id) || empty($user_id)) {
            return false;
        }

        $sql = "UPDATE `l4_photo` SET `view`=`view`+1 WHERE `id`={$user_id}";
        $this->db->queryshort($sql, DB_NAME);

        $sql = "INSERT INTO `l4_photo_view`(`photo_id`,`user_id`) VALUES({$id}, {$user_id})";

        $this->db->queryshort($sql, DB_NAME);
        $affectedRow = $this->db->affectedRow();

        if ($affectedRow > 0) {
            return $this->_countView($id);
        } else {
            return false;
        }

        return false;
    }

    private function _isExist($ip) {
        if (trim($ip) == '') {
            return FALSE;
        }

        $sql = sprintf("SELECT * FROM `l5_sessions` WHERE `ip_address`='%s'", $ip);
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            while ($row = mysql_fetch_object($this->db->result)) {
                return $row;
            }
            return TRUE;
        }
        return NULL;
    }

    private function _likeExisted($id, $user_id) {
        if (empty($id) || empty($user_id)) {
            return FALSE;
        }

        $sql = sprintf("SELECT * FROM `l4_like_photo` WHERE `photo_id`=%s AND `user_id`=%s", $id, $user_id);
        //var_dump($sql);
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            while ($row = mysql_fetch_object($this->db->result)) {
                return $row;
            }
            return TRUE;
        }
        return NULL;
    }

    public static function upload($id) {

        if (empty($_FILES["file"]['name'])) {
            return 'Please choose file image in type of gif, png, jpg, jpeg.';
        }

        if (preg_match('/.*\.(jpg|gif|jpeg|png)$/', $_FILES["file"]["name"])) {
            if ($_FILES["file"]["error"] > 0) {
                return IMAGE_ERROR;
            } else {
                if (file_exists('img/' . $id . '.gif')) {
                    @unlink('img/' . $id . '.gif');
                }
                move_uploaded_file($_FILES["file"]["tmp_name"], "img/" . $_FILES["file"]["name"]);
                rename('img/' . $_FILES["file"]["name"], 'img/' . $id . '.jpeg');
                return '';
            }
        } else {
            return 'Please choose file image in type of gif, png, jpg, jpeg.';
        }
    }

    private function _countLike($id) {
        if (empty($id)) {
            return FALSE;
        }

        $sql = sprintf("SELECT count(*) as `num_like` FROM `l4_like_photo` WHERE `photo_id`=%s", $id);
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            while ($row = mysql_fetch_object($this->db->result)) {
                return $row->num_like;
            }
            return TRUE;
        }
        return NULL;
    }

    private function _countView($id) {
        if (empty($id)) {
            return FALSE;
        }

        $sql = sprintf("SELECT count(*) as `num_view` FROM `l4_photo_view` WHERE `photo_id`=%s", $id);
        $this->db->queryshort($sql, DB_NAME);
        $numRow = $this->db->numRow();

        if ($numRow > 0) {
            while ($row = mysql_fetch_object($this->db->result)) {
                return $row->num_view;
            }
            return TRUE;
        }
        return NULL;
    }

}
?>

